package com.video.main_video.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.video.main_video.common.jwt.JwtUtils;
import com.video.main_video.dao.request.LoginRequest;
import com.video.main_video.dao.response.LoginResponse;
import com.video.main_video.manager.handle.login.LoginManger;
import com.video.main_video.manager.handle.login.LoginOutManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    private LoginManger loginManger;

    @Autowired
    private LoginOutManager loginOutManager;

    @PostMapping("login")
    public LoginResponse login(@RequestBody LoginRequest req, HttpServletResponse res){
        System.out.println("登录");
        LoginResponse loginResponse = loginManger.login(req);
        Cookie cookie = new Cookie("username", req.getUserName());
        res.addCookie(cookie);
        res.setHeader("token",loginManger.token);
        return loginResponse;
    }
    @PostMapping("loginOut")
    public void loginOut(HttpServletRequest req){
        String token = req.getHeader("token");
        DecodedJWT verify = JwtUtils.verify(token);
        if(verify==null){
            return;
        }
        String userName = verify.getClaim("userName").asString();
        System.out.println(userName);
        loginOutManager.loginOut(userName);
        return ;
    }
}
